package com.atguigu.aiproject.aitools;

import com.atguigu.aiproject.config.RabbitMQConfig;
import com.atguigu.aiproject.entity.User;
import com.atguigu.aiproject.service.AdminService;
import com.atguigu.aiproject.vo.MailMessageVO;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class AdminTools {
    private final RabbitTemplate rabbitTemplate;
    private final AdminService adminService;

    public AdminTools(RabbitTemplate rabbitTemplate, AdminService adminService) {
        this.rabbitTemplate = rabbitTemplate;
        this.adminService = adminService;
    }

    @Tool(description = "发送邮件给所有指定id的用户")
    public String sendEmail(@ToolParam(description = "所有要发邮件的用户id") List<Integer> userIds,
                            @ToolParam(description = "邮件主题") String subject,
                            @ToolParam(description = "邮件内容") String content) {

        // 1. 查询用户信息
        List<User> users;
        try {
            users = adminService.getUsersByIds(userIds);
            if (users == null || users.isEmpty()) {
                return "未找到对应的用户";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "查询用户信息失败";
        }

        // 2. 按邮箱分组（避免同一邮箱重复发送）
        Map<String, List<User>> emailUserMap = users.stream()
                .filter(user -> user.getEmail() != null && !user.getEmail().trim().isEmpty())
                .collect(Collectors.groupingBy(User::getEmail));

        // 3. 构建邮件消息列表
        List<MailMessageVO> mailMessageVOs = new ArrayList<>();
        for (Map.Entry<String, List<User>> entry : emailUserMap.entrySet()) {
            String email = entry.getKey();
            List<User> sameEmailUsers = entry.getValue();

            // 合并同一邮箱的多个用户昵称
            String nicknames = sameEmailUsers.stream()
                    .map(User::getNickName)
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining(", "));

            MailMessageVO mailMessageVO = new MailMessageVO(
                    email,
                    nicknames,
                    subject,
                    content,
                    sameEmailUsers.get(0).getId() // 使用第一个用户的ID作为参考
            );
            mailMessageVOs.add(mailMessageVO);
        }

        // 4. 发送消息到RabbitMQ
        try {
            for (MailMessageVO mailMessageVO : mailMessageVOs){
                rabbitTemplate.convertAndSend(
                        RabbitMQConfig.MAIL_DIRECT_EXCHANGE_NAME,
                        RabbitMQConfig.MAIL_DIRECT_ROUTING_KEY,
                        mailMessageVO
                );
            }
            return String.format("邮件任务提交成功，共 %d 封邮件等待发送", mailMessageVOs.size());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("消息队列炸了");
            return "邮件任务提交失败";
        }
    }

    @Tool(description = "SQL执行工具，增、删、改专用，返回执行结果")
    public String executeSql(@ToolParam(description = "sql增、删、改语句") String sql) {
        // 执行SQL并返回结果
        try {
            adminService.executeSql(sql);
        } catch (Exception e) {
            e.printStackTrace();
            return sql + "执行失败\n" + e.getMessage();
        }
        System.out.println("修改：" + sql);

        return "执行成功";
    }
}
